<?php

class UploadImg extends Controller{

	
	
	function __construct(){
		parent::__construct();
		if(!isset($_SESSION["id"])) {echo 'chua log in'; exit;}
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		$this->upload_dir = SVROOT."Media/Photos/Albums/".$_SESSION['id']; 		// The directory for the images to be saved in
		$this->upload_path = $this->upload_dir."/";			// The path to where the image will be saved
		$idUser = $_SESSION["id"];							// Get User id => name img
		$ip_user = $this->f->getRealIPAddress();			// Get Ip user -> name img
		$this->large_image_prefix = "_resize"; 				// The prefix name to large image
		$this->thumb_image_prefix = "_thumbnail";			// The prefix name to the thumb image
		$Latitude = "";			
		$Longitude = "";
		if(isset($_COOKIE["Latitude"])) $Latitude = htmlspecialchars($_COOKIE["Latitude"]);
		if(isset($_COOKIE["Longitude"])) $Longitude = htmlspecialchars($_COOKIE["Longitude"]);
		$this->large_image_name = $idUser.'_'.$timestamp.'_'.'n'.'_'.$Latitude.'_'.$Longitude."_n_n_n".$this->large_image_prefix;     // New name of the large image (append the timestamp to the filename)
		$this->thumb_image_name = $idUser.'_'.$timestamp.'_'.'n'.'_'.$Latitude.'_'.$Longitude."_n_n_n".$this->thumb_image_prefix;     // New name of the thumbnail image (append the timestamp to the filename)
		$this->max_file = "3"; 								// Maximum file size in MB
		$this->max_width = "500";							// Max width allowed for the large image
		$this->thumb_width = "100";							// Width of thumbnail image
		$this->thumb_height = "100";						// Height of thumbnail image
		$this->view->max_file = "3"; 								// Maximum file size in MB
		$this->view->max_width = "500";							// Max width allowed for the large image
		$this->view->thumb_width = "100";							// Width of thumbnail image
		$this->view->thumb_height = "100";						// Height of thumbnail image
		// Only one of these image types should be allowed for upload
		$this->allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
		$this->allowed_image_ext = array_unique($this->allowed_image_types); // do not change this
		$this->image_ext = "";								// initialise variable, do not change this.

		if (!isset($_SESSION['random_key']) || strlen($_SESSION['random_key'])==0){
		    $_SESSION['random_key'] = strtotime(date('Y-m-d H:i:s')); //assign the timestamp to the session variable
			$_SESSION['user_file_ext']= "";
		}
		#########################################################################################################
		# CONSTANTS																								#
		# You can alter the options below																		#
		#########################################################################################################
		
		foreach ($this->allowed_image_ext as $mime_type => $ext) {
		    $this->image_ext.= strtoupper($ext)." ";
		}
	}

	public function resizeImage($image,$width,$height,$scale) {
		list($imagewidth, $imageheight, $imageType) = getimagesize($image);
		$imageType = image_type_to_mime_type($imageType);
		$newImageWidth = ceil($width * $scale);
		$newImageHeight = ceil($height * $scale);
		$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
		switch($imageType) {
			case "image/gif":
				$source=imagecreatefromgif($image); 
				break;
		    case "image/pjpeg":
			case "image/jpeg":
			case "image/jpg":
				$source=imagecreatefromjpeg($image); 
				break;
		    case "image/png":
			case "image/x-png":
				$source=imagecreatefrompng($image); 
				break;
	  	}
		imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
		
		switch($imageType) {
			case "image/gif":
		  		imagegif($newImage,$image);
				break;
	      	case "image/pjpeg":
			case "image/jpeg":
			case "image/jpg":
		  		imagejpeg($newImage,$image,90);
				break;
			case "image/png":
			case "image/x-png":
				imagepng($newImage,$image);
				break;
	    }
		
		chmod($image, 0777);
		return $image;
	}
	//You do not need to alter these functions
	public function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
		list($imagewidth, $imageheight, $imageType) = getimagesize($image);
		$imageType = image_type_to_mime_type($imageType);
		
		$newImageWidth = ceil($width * $scale);
		$newImageHeight = ceil($height * $scale);
		$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
		switch($imageType) {
			case "image/gif":
				$source=imagecreatefromgif($image); 
				break;
		    case "image/pjpeg":
			case "image/jpeg":
			case "image/jpg":
				$source=imagecreatefromjpeg($image); 
				break;
		    case "image/png":
			case "image/x-png":
				$source=imagecreatefrompng($image); 
				break;
	  	}
		imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
		switch($imageType) {
			case "image/gif":
		  		imagegif($newImage,$thumb_image_name); 
				break;
	      	case "image/pjpeg":
			case "image/jpeg":
			case "image/jpg":
		  		imagejpeg($newImage,$thumb_image_name,90); 
				break;
			case "image/png":
			case "image/x-png":
				imagepng($newImage,$thumb_image_name);  
				break;
	    }
		chmod($thumb_image_name, 0777);
		return $thumb_image_name;
	}
	//You do not need to alter these functions
	public function getHeight($image) {
		$size = getimagesize($image);
		$height = $size[1];
		return $height;
	}
	//You do not need to alter these functions
	public function getWidth($image) {
		$size = getimagesize($image);
		$width = $size[0];
		return $width;
	}
	
	public function upload_img () {
		//Image Locations
		$large_image_location = $this->upload_path.$this->large_image_name.$_SESSION['user_file_ext'];
		$thumb_image_location = $this->upload_path.$this->thumb_image_name.$_SESSION['user_file_ext'];
		$_SESSION['large_image_location'] = $large_image_location;
		$_SESSION['thumb_image_location'] = $thumb_image_location;
		//Create the upload directory with the right permissions if it doesn't exist
		if(!is_dir($this->upload_dir)){
			mkdir($this->upload_dir, 0777);
			chmod($this->upload_dir, 0777);
		}

		//Check to see if any images with the same name already exist
		if (file_exists($large_image_location)){
			if(file_exists($thumb_image_location)){
				$this->thumb_photo_exists = "<img src=\"".$this->upload_path.$this->thumb_image_name.$_SESSION['user_file_ext']."\" alt=\"Thumbnail Image\"/>";
			}else{
				$this->thumb_photo_exists = "";
			}
		   	$this->large_photo_exists = "<img src=\"".$this->upload_path.$this->large_image_name.$_SESSION['user_file_ext']."\" alt=\"Large Image\"/>";
		} else {
		   	$this->large_photo_exists = "";
			$this->thumb_photo_exists = "";
		}

		if (isset($_POST["upload"])) { 
			//Get the file information
			$userfile_name = $_FILES['image']['name'];
			$userfile_tmp = $_FILES['image']['tmp_name'];
			$userfile_size = $_FILES['image']['size'];
			$userfile_type = $_FILES['image']['type'];
			$filename = basename($_FILES['image']['name']);
			$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

			//Only process if the file is a JPG, PNG or GIF and below the allowed limit
			if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
				
				foreach ($this->allowed_image_types as $mime_type => $ext) {
					//loop through the specified image types and if they match the extension then break out
					//everything is ok so go and check file size
					if($file_ext==$ext && $userfile_type==$mime_type){
						$error = "";
						break;
					}else{
						$error = "Only <strong>".$this->image_ext."</strong> images accepted for upload<br />";
					}
				}
				//check if the file size is above the allowed limit
				if ($userfile_size > ($this->max_file*1048576)) {
					$error.= "Images must be under ".$this->max_file."MB in size";
				}
				
			}else{
				$error= "Select an image for upload";
			}
			//Everything is ok, so we can upload the image.
			if (strlen($error)==0){
				
				if (isset($_FILES['image']['name'])){
					//this file could now has an unknown file extension (we hope it's one of the ones set above!)
					$large_image_location = $large_image_location;
					$thumb_image_location = $thumb_image_location;
					$this->view->imgLarge = URL.'Media/Photos/Albums/'.$_SESSION['id'].'/'.$this->large_image_name. $_SESSION['user_file_ext'];
					//put the file ext in the session so we know what file to look for once its uploaded
					$_SESSION['img_name'] = $this->large_image_name. $_SESSION['user_file_ext'];
					$_SESSION['user_file_ext']=".".$file_ext;
					move_uploaded_file($userfile_tmp, $large_image_location);
					chmod($large_image_location, 0777);
					
					$width = $this->getWidth($large_image_location);
					$height = $this->getHeight($large_image_location);
					//Scale the image if it is greater than the width set above
					if ($width > $this->max_width){
						$scale = $this->max_width/$width;
						$uploaded = $this->resizeImage($large_image_location,$width,$height,$scale);
					}else{
						$scale = 1;
						$uploaded = $this->resizeImage($large_image_location,$width,$height,$scale);
					}
					//Delete the thumbnail file so the user can create a new one
					if (file_exists($thumb_image_location)) {
						unlink($thumb_image_location);
					}
				}
				//Refresh the page to show the new uploaded image
			}
		}
		$this->view->render('Page/Uploadimg');
	}
	public function upload_thumb () {
		if (isset($_POST["upload_thumbnail"]) && strlen($_SESSION['large_image_location'])>0) {
			//Get the new coordinates to crop the image.
			$x1 = $_POST["x1"];
			$y1 = $_POST["y1"];
			$x2 = $_POST["x2"];
			$y2 = $_POST["y2"];
			$w = $_POST["w"];
			$h = $_POST["h"];
			//Scale the image to the thumb_width set above
			$scale = $this->thumb_width/$w;
			$cropped = $this->resizeThumbnailImage($_SESSION['thumb_image_location'], $_SESSION['large_image_location'],$w,$h,$x1,$y1,$scale);
		}
		header('localtion:'.URL);
	}
	public function save_photo_upload () {
		
		$this->model->save_photo_upload('Media/Photos/Albums/'.$_SESSION['id'].'/');
		
		header('localtion:'.URL);
	}
	public function delete () {
		//if ($_GET['a']=="delete" && strlen($_GET['t'])>0){
			//get the file locations 
		//	$large_image_location = $this->upload_path.$this->large_image_prefix.$_GET['t'];
		//	$thumb_image_location = $this->upload_path.$this->thumb_image_prefix.$_GET['t'];
		//	if (file_exists($_SESSION['large_image_location'])) {
		//		unlink($_SESSION['large_image_location']);
		//	}
		//	if (file_exists($_SESSION['thumb_image_location'])) {
		//		unlink($_SESSION['thumb_image_location']);
		//	}
		//}

		//Only display the javacript if an image has been uploaded
		//if(strlen($this->large_photo_exists)>0){
		//	$current_large_image_width = getWidth($large_image_location);
		//	$current_large_image_height = getHeight($large_image_location);
		//}
	}
}
?>